package com.morgan.maxfunding;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

import java.util.Calendar;

public class FileUploadActivity extends Activity {
	LinearLayout llytHeader;

	EditText edtFullName;
	EditText edtPhone;
	EditText edtEmail;
	Spinner spnFileType;
	
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	private final int REQUEST_CODE_TAKE_PHOTO = 1000;
	
	String strFileName;
	
	Button btnTakePhotoAndUpload;
	LinearLayout llytTakePhotoAndUpload;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_upload);
                
        initWidget();
        initEvent();
        initValue();
        
        //Log.e("phone number", getMy10DigitPhoneNumber());
    }
    
    private void initWidget() {
    	
		llytHeader			= (LinearLayout) findViewById(R.id.header_linearLayout);

    	edtFullName = (EditText) findViewById(R.id.file_upload_full_name_editText);
    	edtPhone = (EditText) findViewById(R.id.file_upload_phone_editText);
    	edtEmail = (EditText) findViewById(R.id.file_upload_email_editText);
    	spnFileType = (Spinner) findViewById(R.id.file_upload_file_type_spinner);
    	
    	btnTakePhotoAndUpload = (Button) findViewById(R.id.index_submit_button);
    	llytTakePhotoAndUpload = (LinearLayout) findViewById(R.id.take_photo_upload_layout);

    }
//    
//    private String getMyPhoneNumber(){
////        TelephonyManager mTelephonyMgr;
////        mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
////        String str = mTelephonyMgr.getDeviceId();
////        return str;
//    }
//
//    private String getMy10DigitPhoneNumber(){
//    	String s = getMyPhoneNumber();
//    	
//        return s.substring(2);
//    }
    
    private void initEvent() {
    	
		llytHeader.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maxfunding.com.au"));
				startActivity(browserIntent);
			}
        });
		
    	btnTakePhotoAndUpload.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				if (!checkInput())
		    		return;
				
				File f = null;
 				Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

 				f = getPhotoFile();
// 					strCarRegoStickerPath2 = f.getAbsolutePath();
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
 				
 			    startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO);
			}
        });
    	
    	llytTakePhotoAndUpload.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				if (!checkInput())
		    		return;
				
				File f = null;
 				Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

 				f = getPhotoFile();
// 					strCarRegoStickerPath2 = f.getAbsolutePath();
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
 				
 			    startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO);
			}
        });
    	
    	edtPhone.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {

              // you can call or do what you want with your EditText here
            	String str = edtPhone.getText().toString();
            	int l = str.length();
            	if (l > 10) {
                	String strMobilePhone = str.substring(0, 10);
                	edtPhone.setText(strMobilePhone);
                	edtPhone.setSelection(10);
            	}
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
        });
    }
    
    private void initValue() {
    	ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, GlobalData.itemsOfFileType);
		spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
		spnFileType.setAdapter(spinnerArrayAdapter);
    }
    
    private File getPhotoFile() {
	    String filePath = Environment.getExternalStorageDirectory().getPath();
		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		
		String fullName = edtFullName.getText().toString();
		String email = edtEmail.getText().toString();
		String phone = edtPhone.getText().toString();
//		
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
		String currentDateandTime = sdf.format(c.getTime());
	
		strFileName = fullName + "_" + email + "_" + phone + "_" + currentDateandTime + JPEG_FILE_SUFFIX;
		strFileName = strFileName.replace(" ", "_");

		Log.e("fileName: ", strFileName);
		File tempFile = new File(filePath, strFileName);
		
		return tempFile;
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("test", "onActivityResult");

		if (resultCode == RESULT_OK) {
			Log.e("test", "resultCode");

			/*
			 * btnUploadDriverLicense.setOnClickListener(new
			 * Button.OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { if (strDriverLicensePath
			 * == null) return;
			 * 
			 * try { new MyAsyncTask(CompleteActivity.this).execute("upload",
			 * strAppID, DRIVER_LICENSE_TYPE, strDriverLicensePath); } catch
			 * (Exception e) {
			 * 
			 * } } });
			 * 
			 * btnUploadCarRegoSticker1.setOnClickListener(new
			 * Button.OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { if
			 * (strCarRegoStickerPath1 == null) return; new
			 * MyAsyncTask(CompleteActivity.this).execute("upload", strAppID,
			 * CAR_REGO1_TYPE, strCarRegoStickerPath1); } });
			 * 
			 * btnUploadCarRegoSticker2.setOnClickListener(new
			 * Button.OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { if
			 * (strCarRegoStickerPath2 == null) return; new
			 * MyAsyncTask(CompleteActivity.this).execute("upload", strAppID,
			 * CAR_REGO2_TYPE, strCarRegoStickerPath2); } });
			 * 
			 * btnUploadBankTransaction.setOnClickListener(new
			 * Button.OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { if (strBankTransationPath
			 * == null) return; new
			 * MyAsyncTask(CompleteActivity.this).execute("upload", strAppID,
			 * BANK_TRANSACTION_TYPE, strBankTransationPath); } });
			 */

			if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
				// imgDriverLicense.setImageBitmap(getPicture(strDriverLicensePath));

				if (strFileName == null)
					return;
				
				Log.e("test", "requestCode");

				SharedPreferences sharedPreferences = MainActivity.sharedPreferences;
				
				String strAppID = sharedPreferences.getString("appID", "0");
				String fullName = edtFullName.getText().toString();
				String email = edtEmail.getText().toString();
				String phone = edtPhone.getText().toString();
				String fileType = GlobalData.itemsOfFileType[(int) spnFileType.getSelectedItemId()];
				
				new MyAsyncTask(FileUploadActivity.this, MyAsyncTask.ACTION_FILE_UPLOAD_FIRST).execute(MyAsyncTask.ACTION_FILE_UPLOAD_FIRST,
						strAppID, fullName, email, phone, fileType, strFileName);
			}
		}

		if (resultCode == RESULT_CANCELED) {
			strFileName = null;
		}
	}
    
    public void showGeneralAlert(String title, String message) {
    	new AlertDialog.Builder(FileUploadActivity.this)
        .setTitle(title)
        .setMessage(message)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                // continue with delete
            }
         })
         .show();
    }
    
    public boolean checkInput() {
    	String str;
    	
    	str = edtFullName.getText().toString();
    	if (str.equals("")) {
    		showGeneralAlert("Input", "Please input your full name!");
    		edtFullName.requestFocus();

    		return false;
    	}
    	str = edtPhone.getText().toString();
    	if (str.equals("")) {
    		showGeneralAlert("Input", "Please input your Mobile phohe number!");
    		edtPhone.requestFocus();
    		
    		return false;
    	}

    	String strFirst;
    	
    	strFirst = str.substring(0, 2);
    	int l = str.length();
    	if (!strFirst.equals("04") || l != 10) {
    		showGeneralAlert("Input", "Your Mobile phohe number has wrong format!");
    		edtPhone.requestFocus();

    		return false;
    	}
//    	str = GlobalData.itemsOfFileType[spnFileType.getSelectedItemPosition()];;
//    	if (str.equals("")) {
//    		showGeneralAlert("Input", "Please select file type!");
//    		spnFileType.requestFocus();
//
//    		return false;
//    	}
    	
    	return true;
    }
}